﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Runtime.Serialization;
using System.Yaml.Serialization;
using log4net;
using Reactor.Environment;

namespace Reactor.Messaging.ServiceBus.Internals
{
    public class SqlSubscriptionDataProvider : ISubscriptionDataProvider
    {
        #region Fields

        private readonly string _connectionString;
        private readonly YamlSerializer _serializer = new YamlSerializer();
        private static readonly ILog Log = LogManager.GetLogger(typeof(SqlSubscriptionDataProvider));

        #endregion

        #region Constructors

        /// <summary>
        /// Initializes a new instance of the <see cref="SqlSubscriptionDataProvider"/> class.
        /// </summary>
        /// <param name="platformConnectionData">The platform connection data.</param>
        public SqlSubscriptionDataProvider(PlatformConnectionData platformConnectionData)
        {
            if (platformConnectionData == null) throw new ArgumentNullException("platformConnectionData");
            if(string.IsNullOrEmpty(platformConnectionData.DatabaseConnectionString)) throw new InvalidOperationException("Cannot initialize without platform database connection string.");

            _connectionString = platformConnectionData.DatabaseConnectionString;
        }

        #endregion

        #region ISubscriptionDataProvider Members

        /// <summary>
        /// Obtains all data necessary to construct and return all Subscribers.
        /// </summary>
        /// <returns>Array of <see cref="Subscriber"/>s</returns>
        public Subscriber[] GetAllSubscribers()
        {
            var rawSubscriberData = new Dictionary<string, string>();
            var results = new List<Subscriber>();

            try
            {
                using (var sqlConnection = new SqlConnection(_connectionString))
                {
                    using (var cmd = new SqlCommand("dbo.rsb_GetAllSubscribers"))
                    {
                        cmd.CommandType = CommandType.StoredProcedure;
                        sqlConnection.Open();
                        cmd.Connection = sqlConnection;

                        using (var rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection))
                        {
                            while (rdr.Read())
                            {
                                var subscriberName = rdr.GetString(rdr.GetOrdinal("SubscriberName"));
                                var destinationMappings = rdr.GetString(rdr.GetOrdinal("SerializedSubscriber"));

                                if (!rawSubscriberData.ContainsKey(subscriberName))
                                    rawSubscriberData.Add(subscriberName, destinationMappings);
                            }
                        }
                    }
                }

                //Create subscriber instances from what we found in the database
                foreach (var kvp in rawSubscriberData)
                {
                    try
                    {
                        var subscriber = CreateSubscriber(kvp.Value);
                        results.Add(subscriber);
                    }
                    catch (Exception e)
                    {
                        if (Log.IsErrorEnabled)
                            Log.Error(string.Format("Cannot deserialize Subscriber named '{0}'", kvp.Value), e);
                    }
                }
            }
            catch(Exception ex)
            {
                if (Log.IsErrorEnabled)
                    Log.Error("Unable to retrieve subscription data. Switching to passive mode.", ex);
            }

            return results.ToArray();
        }

        /// <summary>
        /// Obtains all data necessary to construct and return a <see cref="Subscriber"/>. Looks
        /// the subscription record up by the subscriber's name.
        /// </summary>
        /// <param name="subscriberName">Name of the subscriber.</param>
        /// <returns><see cref="Subscriber"/> instance</returns>
        public Subscriber GetSubscriberByName(string subscriberName)
        {
            try
            {
                using (var sqlConnection = new SqlConnection(_connectionString))
                {
                    using (var cmd = new SqlCommand("dbo.rsb_GetSubscriber"))
                    {
                        cmd.CommandType = CommandType.StoredProcedure;
                        cmd.Parameters.AddWithValue("@SubscriberName", subscriberName);
                        sqlConnection.Open();
                        cmd.Connection = sqlConnection;

                        using (var rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection))
                        {
                            var serializedSubscriber = string.Empty;

                            while (rdr.Read())
                            {
                                serializedSubscriber = rdr.GetString(rdr.GetOrdinal("SerializedSubscriber"));
                            }

                            if (!string.IsNullOrEmpty(serializedSubscriber))
                                return CreateSubscriber(serializedSubscriber);
                        }
                    }
                }

                return null;
            }
            catch (Exception e)
            {
                if (Log.IsErrorEnabled)
                    Log.Error(string.Format("Unable to retrieve subscriber data for subscriber: {0}", subscriberName), e);
            }

            return null;
        }

        /// <summary>
        /// Saves the provided subscriber instance.
        /// </summary>
        /// <param name="subscriber">The subscriber to be saved.</param>
        /// <exception cref="ArgumentNullException">Throws an ArgumentNullException if the <paramref name="subscriber"/> parameter is null.</exception>
        public void SaveSubscriber(Subscriber subscriber)
        {
            if (subscriber == null) throw new ArgumentNullException("subscriber");

            try
            {
                var serializedSubscriber = _serializer.Serialize(subscriber);

                using (var sqlConnection = new SqlConnection(_connectionString))
                {
                    using (var cmd = new SqlCommand("dbo.rsb_RegisterSubscriber"))
                    {
                        cmd.CommandType = CommandType.StoredProcedure;
                        cmd.Parameters.AddWithValue("@SubscriberName", subscriber.Name);
                        cmd.Parameters.AddWithValue("@SerializedSubscriber", serializedSubscriber);
                        sqlConnection.Open();
                        cmd.Connection = sqlConnection;
                        cmd.ExecuteNonQuery();
                    }
                }
            }
            catch (Exception e)
            {
                if (Log.IsErrorEnabled)
                    Log.Error(string.Format("Unable to save subscription data for subscriber: {0}.", subscriber.Name), e);
            }
        }

        #endregion

        #region Private Members

        private Subscriber CreateSubscriber(string serializedSubscriber)
        {
            var objects = _serializer.Deserialize(serializedSubscriber, typeof(Subscriber.ChannelMessagesMapping));
            if (objects.Length == 0) throw new SerializationException("Cannot deserialize Subscriber.");

            return (Subscriber)objects[0];
        }

        #endregion
    }
}
